/*
 * @lc app=leetcode.cn id=114 lang=cpp
 *
 * [114] 二叉树展开为链表
 */
#include "include.h"

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};

// @lc code=start
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    void flatten(TreeNode* root) {
        if (!root) {return;}
        reversePreorderTraverse(root);
    }
private:
    TreeNode* nextNodePtr_ = nullptr;
    void reversePreorderTraverse(TreeNode* root){
        if (root->right) {reversePreorderTraverse(root->right);}
        if (root->left) {reversePreorderTraverse(root->left);}
        // root
        root->left = nullptr;
        root->right = nextNodePtr_;
        nextNodePtr_ = root;
    }
};
// @lc code=end

